﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Data.DBModels;
using Data.MyDbContext;
using System.Net;
using DAL;
using Utilities;

namespace WebIndex1.Controllers
{
    public class WebsiteController : Controller
    {
        private readonly IUnitOfRepositories _repositories=null;
        public WebsiteController(IUnitOfRepositories repositories)
        {
            _repositories = repositories;
        }
        //
        // GET: /Website/

        public ActionResult Index()
        {
            return View(_repositories.WebsiteRepo.GetAllOrderByDesc(o=>o.ModifiedOn));
        }

        //
        // GET: /Website/Details/5

        public ActionResult Details(Guid id)
        {
            Website website = _repositories.WebsiteRepo.Find(id);
            if (website == null)
            {
                return new EmptyResult();
            }
            return View(website);
        }

        //
        // GET: /Website/Create

        public ActionResult Create()
        {
            ViewBag.Categories = _repositories.CategoryRepo.GetAll();
            return View();
        }

        //
        // POST: /Website/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Website website)
        {
            if (ModelState.IsValid)
            {
                
                website.Id = Guid.NewGuid();
                website.CreatedOn = DateTime.Now;
                if (User.Identity.IsAuthenticated)
                {
                    website.Categories.FirstOrDefault().CreatedBy = _repositories.UserRepo.GetUser(User.Identity.Name);
                }
                _repositories.WebsiteRepo.Add(website);
                return RedirectToAction("Index");
            }

            return View(website);
        }

        //
        // GET: /Website/Edit/5

        public ActionResult Edit(Guid id)
        {
            Website website = _repositories.WebsiteRepo.Find(id);
            if (website == null)
            {
                return new EmptyResult();
            }
            return View(website);
        }

        //
        // POST: /Website/Edit/5


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Guid? id, string[] selectedCategories)
        {

            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            

            var websiteToUpdate = _repositories.WebsiteRepo.Find(id.Value);

            TryUpdateModel(websiteToUpdate, "", null, new string[] { "CreatedOn", "Categories" });
            websiteToUpdate.ModifiedOn = DateTime.Now;
            bool updated = _repositories.WebsiteRepo.UpdateWithCategories(websiteToUpdate, selectedCategories.Select(item=>new Guid(item)).ToArray());
            if (updated)
            {
                return RedirectToAction("Index");
            }
            else
            {
                return View(websiteToUpdate);
            }
        }


        //
        // GET: /Website/Edit/5
        [Authorize]
        public ActionResult EditPopUp(Guid? id, Guid? categoryId=null)
        {
            Website website = new Website();
            if(id.IsValid())
            {
                website = _repositories.WebsiteRepo.Find(id.Value);
                if (website == null || Helper.GetUser(_repositories.UserRepo) != website.CreatedBy)
                {
                    return HttpNotFound();
                }
            }
            else if(categoryId.IsValid())
            {
                website.Categories=new List<Category>();
                website.Categories.Add(_repositories.CategoryRepo.Find(categoryId.Value));
            }
            return PartialView("_editPopup", website);
        }

        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        //[ChildActionOnly]
        public ActionResult EditPopUp(Guid? id, string[] selectedCategories)
        {
            bool issucceed = false;
            Website websiteToUpdate = null;
            if (!id.IsValid())
            {
                websiteToUpdate = new Website();

                TryUpdateModel(websiteToUpdate, "", null, new string[] { "CreatedOn", "Categories","CreatedBy" });
                websiteToUpdate.Id = Guid.NewGuid();

                websiteToUpdate.CreatedOn = DateTime.Now;
                websiteToUpdate.ModifiedOn = DateTime.Now;
                issucceed = _repositories.WebsiteRepo.CreateWithCategories(websiteToUpdate, selectedCategories.Select(item => new Guid(item)).ToArray());

                if (issucceed) return RedirectToAction("DisplayAllCategoriesPartial", "Category"); //RedirectToAction("Main", "Home");// PartialView("_DisplayWebsitesInCategory", websiteToUpdate.Categories.First());
            }
            else
            {

                websiteToUpdate = _repositories.WebsiteRepo.Find(id.Value);

                if (websiteToUpdate == null || Helper.GetUser(_repositories.UserRepo) != websiteToUpdate.CreatedBy)
                {
                    return HttpNotFound();
                }

                TryUpdateModel(websiteToUpdate, "", null, new string[] { "CreatedOn", "Categories", "CreatedBy", "CreatedBy_Id" });
                websiteToUpdate.ModifiedOn = DateTime.Now;
                
                issucceed = _repositories.WebsiteRepo.UpdateWithCategories(websiteToUpdate, selectedCategories.Select(item => new Guid(item)).ToArray());
                 if (issucceed)
                {
                    return PartialView("_Website", websiteToUpdate);
                }
            }

           
                return new EmptyResult();
            
           

        }


        


       

        //
        // POST: /Website/Delete/5
        [Authorize]
        [HttpPost, ActionName("Delete")]
        //[ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(Guid id)
        {
            if (_repositories.WebsiteRepo.Delete(id)) return RedirectToAction("DisplayAllCategoriesPartial", "Category");
            return View();
        }

 
    }
}